﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.WindowsServerSolutions.Wizards;

namespace TV4Home.Server.Vail.AddIn.Wizards.UninstallTVServer
{
    public partial class WPUninstallationControl : WizardPage
    {
        public WPUninstallationControl()
        {
            InitializeComponent();
        }

        public bool UninstallComponents(bool standardUninstall)
        {
            bool result = false;

            bgwUninstall.RunWorkerCompleted += (sender, e) => result = (bool)e.Result;
            bgwUninstall.RunWorkerAsync(standardUninstall);

            // wait until completion
            while (bgwUninstall.IsBusy)
            {
                System.Threading.Thread.Sleep(100);
                Application.DoEvents();
            }

            return result;
        }

        private void UninstallNSISWithArguments(string RegistryFullPathName, string arguments)
        {
            string FileName = Path.GetFileName(RegistryFullPathName);
            string Directory = Path.GetDirectoryName(RegistryFullPathName);
            string TempFullPathName = Environment.GetEnvironmentVariable("TEMP") + "\\" + FileName;
            File.Copy(RegistryFullPathName, TempFullPathName, true);
            Process setup = Process.Start(TempFullPathName, " /S _?=" + Directory + arguments);
            if (setup != null)
            {
                setup.WaitForExit();
            }
            File.Delete(TempFullPathName);
        }

        private void bgwUninstall_DoWork(object sender, DoWorkEventArgs e)
        {
            bool standardUninstall = (bool)e.Argument;

            try
            {
                UninstallNSISWithArguments(MediaPortal.DeployTool.Utils.CheckUninstallString("MediaPortal TV Server", false), standardUninstall ? "" : " /RemoveAll");
            }
            catch (Exception)
            {
                e.Result = false;
            }

            e.Result = true;
        }
    }
}
